##
rm(list=ls())
gc()

library(ggplot2)
library(scales)
library(data.table)

library(lfe)
library(stringr)





data = rbindlist(lapply(c('panel-analysis-2008-2012.csv.gz',
                          'panel-analysis-2012-2016.csv.gz',
                          'panel-analysis-2016-2020.csv.gz'), FUN = function(x){
  d=fread(x, select = c('Unique_ID','voterbase_id','voterbase_id_year1','voterbase_id_year2', 'DemSpExp_nohh_year1','RepSpExp_nohh_year1',
                        'RepSpExp_nohh_alt_year1', 'RepSpExp_nohh_alt_year2',
                        'DemSpExp_nohh_alt_year1', 'DemSpExp_nohh_alt_year2'))[,Years:=str_replace(str_replace(x, '.csv.gz', ''),'panel-analysis-','')]
                          
  
  if(grepl('2008-2012',x)){
    
  
    d[,DemSpExpDiff_nohh:=DemSpExp_nohh_alt_year2-DemSpExp_nohh_year1]
    d[,RepSpExpDiff_nohh:=RepSpExp_nohh_alt_year2-RepSpExp_nohh_year1]
    
  } else {
    
    d[,DemSpExpDiff_nohh:=DemSpExp_nohh_alt_year2-DemSpExp_nohh_alt_year1]
    d[,RepSpExpDiff_nohh:=RepSpExp_nohh_alt_year2-RepSpExp_nohh_alt_year1]
    
  } 
    
  return(d[,c('DemSpExpDiff_nohh','RepSpExpDiff_nohh','Years')])
  
  }))



## Make Plots 

# let's make a sample dataset just to make these plots


holder1 = data[,c('DemSpExpDiff_nohh','Years')]
holder1[,Exposure:=DemSpExpDiff_nohh][,Exposure.Type:='Exposure\nto Democrats']
holder1= holder1[,c('Exposure','Exposure.Type', 'Years')]

holder2 = data[,c('RepSpExpDiff_nohh','Years')]
holder2[,Exposure:=RepSpExpDiff_nohh][,Exposure.Type:='Exposure\nto Republicans']
holder2= holder2[,c('Exposure','Exposure.Type', 'Years')]

holder = rbind(holder1,holder2)

rm(holder1,holder2)
gc()

colors = c(`Exposure\nto Democrats` = "#377EB8",`Exposure\nto Republicans` = "#E41A1C")



g=  ggplot(data=holder, aes(x=Exposure,color=Exposure.Type, linetype=Years))+
  geom_density()+
  theme_bw()+
  facet_grid(rows = vars(Exposure.Type))+
  scale_linetype_manual(values=c('dotted','dashed', 'solid'))+
  theme(legend.position='bottom', legend.title=element_blank(), text=element_text(size=18))+
  scale_color_manual(values=colors) +
  xlim(-.5,.5)+
  theme(text=element_text(family='serif', size = 24))+
  xlab('')+
  ylab('Density')+
  guides(color='none')


library(modelsummary)
library(gt)
library(tidyr)

names(data) = c( 'Exposure\nto Democrats', 'Exposure\nto Republicans', 'Years')
###
library(dplyr)
library(tibble)
library(glue)
library(scales)


d = holder[,list(Mean=mean(Exposure,na.rm=T), Median=median(Exposure,na.rm=T),SD=sd(Exposure,na.rm=T)),by=c('Years','Exposure.Type')]%>%
  as_tibble()%>%
  pivot_longer(Mean:SD)

library(dplyr)
d = d %>% mutate(Exposure.Type=factor(Exposure.Type, levels = c('Exposure\nto Republicans','Exposure\nto Democrats')))
#colors = c(Dem. = '#377EB8', Rep. = '#E41A1C')


theme_jake_tile2 <- function(base_size = 10, base_family = "serif",
                             base_line_size = base_size / 22,
                             base_rect_size = base_size / 22) {
  # Starts with theme_bw and remove most parts
  theme_bw(
    base_size = base_size,
    base_family = base_family,
    base_line_size = base_line_size,
    base_rect_size = base_rect_size
  ) %+replace%
    theme(
      plot.title = element_text(size = 15),
      panel.grid.major = element_blank(), 
      panel.grid.minor = element_blank(),
      axis.ticks      = element_blank(),
      legend.background = element_blank(),
      legend.key        = element_blank(),
      panel.background  = element_blank(),
      panel.border      = element_blank(),
      strip.background  = element_blank(),
      plot.background   = element_blank(),
      legend.position   = 'none',
      # axis.title.x=element_blank()
      
      complete = TRUE
    )
}
d$y=1

d$value=round(d$value, digits = 2)
d$value=ifelse(d$value==0,0,d$value)
t=ggplot(d,aes(y=Exposure.Type, x = name,fill=Exposure.Type,  label = sprintf("%0.2f", value)))+
  geom_tile(alpha=.75)+
  scale_fill_manual(values=colors)+
  geom_text( size = 5, alpha =1, color='black') +
  scale_x_discrete(position = "top") +
  scale_y_discrete(position = "right") +
  geom_vline(xintercept = 1:8 - 0.5, colour = "white", size = 1) +
  geom_hline(yintercept = 1:8 - 0.5, colour = "white", size = 1) +
  ylab("") +  
  xlab('') +
  coord_equal() +
  theme_jake_tile2()+
  theme(text=element_text(size=24, family='serif'), legend.title=element_blank(),strip.placement='outside', axis.text.y=element_blank(),legend.position='bottom')+
  facet_grid(cols = vars(Years))#+


library(cowplot)

ggsave(filename = 'figures/FigS13.png', width = 11, height=11,units = 'in',
       plot = plot_grid(g,t,ncol=1,align='v'))




